{% extends "base.html" %}
{% block content %}
{% if request.user.is_student %}
    {% if topic.student == request.user and topic.status == 'applied' %}
        <form action="{% url 'delete_topic_selection' topic.id %}" method="post" style="display: inline;">
          {% csrf_token %}
          <button type="button" class="btn btn-danger" onclick="confirmDelete(this)">删除</button>
        </form>
    {% endif %}
{% endif %}
    <div class="card shadow-sm p-4 mb-4 bg-white rounded">
    <form method="get" class="row g-3 align-items-center">
        <!-- 在查询表单中新增一个筛选项 -->
        <div class="col-auto">
            <select name="filter" class="form-select">
                <option value="" disabled selected>全部申请</option>
                <option value="pending">待审核</option>
            </select>
        </div>
        <div class="col-auto">
            <input type="text" name="student" class="form-control" placeholder="学生名称" value="{{ request.GET.student }}">
        </div>
        <div class="col-auto">
            <input type="text" name="topic" class="form-control" placeholder="题目名称" value="{{ request.GET.topic }}">
        </div>
        <div class="col-auto">
            <select name="status" class="form-select" >
                <option value="" disabled selected>选择状态</option>
                <option value="applied">已申请</option>
                <option value="approved">已通过</option>
                <option value="rejected">未通过</option>
                <option value="dropped">已退题</option>
            </select>
        </div>
        <div class="col-auto">
            <button type="submit" class="btn btn-primary">查询</button>
        </div>
    </form>
</div>


<div>
      <div style="margin-bottom: 10px;">
        <button type="button" class="btn btn-primary create-btn" data-bs-toggle="modal" data-bs-target="#questionModal">
            创建选题
        </button>
  <div class="modal fade" id="topicModal" tabindex="-1" aria-labelledby="topicModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="topicModalLabel">选题管理</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="topicForm" method="post">
                    {% csrf_token %}
                    <input type="hidden" name="id" id="topicId"> <!-- 编辑时使用 -->

                    <div class="mb-3">
                        <label for="studentSelect" class="form-label">学生</label>
                        {% if request.user.role == 'student' %}
                        <!-- 学生登录时自动填充自己的ID，隐藏真实字段，显示用户名 -->
                            <input type="text" class="form-control" value="{{ request.user.username }}" disabled>
                            <input type="hidden" id="studentInput" name="student" value="{{ request.user.id }}">
                        {% else %}
                        <!-- 教师或管理员可选择学生 -->
                        <select class="form-select" id="studentSelect" name="student" required>
                            <option value="">请选择学生</option>
                            {% for student in students %}
                                <option value="{{ student.id }}">{{ student.username }}</option>
                            {% endfor %}
                        </select>
                        {% endif %}
                    </div>

                   <div class="mb-3">
                        <label for="topicSelect" class="form-label">题目</label>
                        <select class="form-select" id="topicSelect" name="topic" required>
                            <option value="">请选择题目</option>
                            {% for topic in topics %}
                                {% if request.user.role == 'teacher' %}
                                    {% if topic.created_by == request.user %}
                                        <option value="{{ topic.id }}">{{ topic.title }}</option>
                                    {% endif %}
                                {% else %}
                                    <option value="{{ topic.id }}">{{ topic.title }}</option>
                                {% endif %}
                            {% endfor %}
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="statusSelect" class="form-label">状态</label>
                            {% if request.user.role == 'student' %}
                            <!-- 学生只能填“已申请”，隐藏选择框 -->
                                <input type="text" class="form-control" value="已申请" disabled>
                                <input type="hidden" id="statusInput" name="status"  value="applied">
                            {% else %}
                            <!-- 教师/管理员可以自由选择 -->
                        <select class="form-select" id="statusSelect" name="status" required>
                            <option value="applied">已申请</option>
                            <option value="approved">已通过</option>
                            <option value="rejected">未通过</option>
                            <option value="dropped">已退题</option>
                        </select>
                            {% endif %}
                    </div>

                    <div class="mb-3">
                        <label for="approveTime" class="form-label">审核时间（可选）</label>
                        <input type="datetime-local" class="form-control" id="approveTime" name="approve_time">
                    </div>

                    <div class="mb-3">
                        <label for="comment" class="form-label">审核意见（可选）</label>
                        <textarea class="form-control" id="comment" name="comment" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="submit" class="btn btn-primary" id="submitTopicBtn">保存</button>
            </div>
        </div>
    </div>
</div>
</div>
    <div class="card shadow-sm p-4 mb-4 bg-white rounded">
        <style>               
         tr,td {
             text-align: center;
             vertical-align: middle;
             
         }
        </style>
        <table class="table table-hover">
            <thead>
            <tr>
                <th scope="col">ID</th>
                <th scope="col">学生</th>
                <th scope="col">题目</th>
                <th scope="col">状态</th>
                <th scope="col">审核时间</th>
                <th scope="col">审核意见</th>
                <th scope="col">操作</th>
            </tr>
            </thead>
            <tbody>
            {% for topic in topic %}
            <tr>
                <th scope="row" >{{ topic.id }}</th>
                <td>{{ topic.student}}</td>
                <td>{{ topic.topic }}</td>
                <td>{{ topic.status }}</td>
                <td>{{ topic.apply_time | date:"Y-m-d H:i:s"}}</td>
                <td>{{ topic.comment }}</td>
                <td>
                    {% if request.user.is_teacher %}
                        {% if topic.status == "applied" %}
                    <button type="button" class="btn btn-success approve-btn"
                            data-id="{{ topic.id }}"
                            data-status="approved"
                            data-student="{{ topic.student.id }}"
                            data-topic="{{ topic.topic.id }}"
                            data-bs-toggle="modal"
                            data-bs-target="#topicModal">
                        批准
                    </button>
                    <button type="button" class="btn btn-danger reject-btn"
                            data-id="{{ topic.id }}"
                            data-status="rejected"
                            data-student="{{ topic.student.id }}"
                            data-topic="{{ topic.topic.id }}"
                            data-bs-toggle="modal"                            data-bs-target="#topicModal">
                        驳回
                    </button>

                    {% endif %}

                  {% endif %}

                    <button type="button" class="btn btn-primary edit-btn"
                        data-bs-toggle="modal" data-bs-target="#topicModal"
                        data-id="{{ topic.id }}"
                        data-student="{{ topic.student.id }}"
                        data-topic="{{ topic.topic.id }}"
                        data-status="{{ topic.status }}"
                        data-approve-time="{{ topic.approve_time|date:'Y-m-d\\TH:i' }}"
                        data-comment="{{ topic.comment }}">
                        编辑
                     </button>
                    <form action="{% url 'delete_topic_selection' topic.id %}" method="post" style="display: inline;">
                      {% csrf_token %}
                     <button type="button" class="btn btn-danger" onclick="confirmDelete(this)">
                     删除
                     </button>
                 </form>
                </td>
            </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>
    </div>

<div class="d-flex justify-content-between align-items-center mt-3">
    <nav>
        <ul class="pagination mb-0">
            {% if topic.has_previous %}
                <li class="page-item">
                    <a class="page-link" href="?page={{ topic.previous_page_number }}&student={{ request.GET.student }}&topic={{ request.GET.topic }}&status={{ request.GET.status }}">上一页</a>
                </li>
            {% else %}
                <li class="page-item disabled">
                    <a class="page-link" href="#">上一页</a>
                </li>
            {% endif %}

            {% for num in topic.paginator.page_range %}
                {% if num == topic.number %}
                    <li class="page-item active"><a class="page-link" href="#">{{ num }}</a></li>
                {% else %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ num }}&student={{ request.GET.student }}&topic={{ request.GET.topic }}&status={{ request.GET.status }}">{{ num }}</a>
                    </li>
                {% endif %}
            {% endfor %}

            {% if topic.has_next %}
                <li class="page-item">
                    <a class="page-link" href="?page={{ topic.next_page_number }}&student={{ request.GET.student }}&topic={{ request.GET.topic }}&status={{ request.GET.status }}">下一页</a>
                </li>
            {% else %}
                <li class="page-item disabled">
                    <a class="page-link" href="#">下一页</a>
                </li>
            {% endif %}
        </ul>
    </nav>

    <span class="text-muted">当前页 {{ topic.number }} / 共 {{ total_pages }} 页</span>
</div>

<style>
.pagination {
    margin: 0;
}
.page-link {
    color: #007bff;
}
.page-item.active .page-link {
    background-color: #007bff;
    border-color: #007bff;
    color: white;
}
</style>

<script>
    // 处理批准/驳回按钮点击事件
    document.querySelectorAll('.approve-btn, .reject-btn').forEach(button => {
    button.addEventListener('click', function () {
        const id = this.getAttribute('data-id');
        const status = this.getAttribute('data-status');
        const student = this.getAttribute('data-student');
        const topic = this.getAttribute('data-topic');

        // 填充表单字段
        document.getElementById('topicId').value = id;
        document.getElementById('statusSelect').value = status;
        document.getElementById('studentSelect').value = student;
        document.getElementById('topicSelect').value = topic;

        // 显示模态框
        modal.show();
    });
});
    function confirmDelete(button) {
    if (confirm('确定要删除这个选题吗？')) {
        const form = button.closest('form');
        const url = form.action;

        fetch(url, {
            method: 'POST',
            headers: {
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: new FormData(form)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('删除成功');
                window.location.reload(); // 刷新页面获取最新数据
            } else {
                alert('删除失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('请求失败:', error);
            alert('网络错误，请重试');
        });
    }
}

document.addEventListener('DOMContentLoaded', function () {
    const modal = new bootstrap.Modal(document.getElementById('topicModal'));
    const form = document.getElementById('topicForm');
    const submitBtn = document.getElementById('submitTopicBtn');

    // 初始化表单
    function resetForm() {
        form.reset();
        document.getElementById('topicId').value = '';
        submitBtn.textContent = '保存';
    }

    // 点击【创建选题】按钮时触发
    document.querySelector('.create-btn').addEventListener('click', function () {
        resetForm();  // 清空表单
        modal.show(); // 显示模态框
    });

    // 给所有 .edit-btn 添加点击事件监听器
    document.querySelectorAll('.edit-btn').forEach(button => {
        button.addEventListener('click', function () {
            // 获取 data-* 属性中的数据
            const id = this.getAttribute('data-id');
            const student = this.getAttribute('data-student');
            const topic = this.getAttribute('data-topic');
            const status = this.getAttribute('data-status');
            const approveTime = this.getAttribute('data-approve-time');
            const comment = this.getAttribute('data-comment');

            // 填充表单字段
            document.getElementById('topicId').value = id;
            document.getElementById('studentSelect').value = student;
            document.getElementById('topicSelect').value = topic;
            document.getElementById('statusSelect').value = status;
            document.getElementById('approveTime').value = approveTime || '';
            document.getElementById('comment').value = comment || '';

            submitBtn.textContent = '更新';

            // 显示模态框
            modal.show();
        });
    });

    // 表单提交逻辑（已存在）
    submitBtn.addEventListener('click', function (e) {
        e.preventDefault();

        const formData = new FormData(form);
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
        const topicId = document.getElementById('topicId').value;

        const url = topicId ? `/topic/${topicId}/update/` : `/topic/create/`;

        fetch(url, {
            method: 'POST',
            headers: {
                'X-CSRFToken': csrfToken,
            },
            body: formData,
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(data.message);
                window.location.reload(); // 刷新页面获取最新数据
            } else {
                alert(data.message);
            }
        })
        .catch(error => {
            console.error('请求失败:', error);
            alert('网络请求失败，请重试');
        });
    });
});

</script>

{% endblock %}
